package DBLayer;
import ModelLayer.*;
import java.sql.*;


public class DBLeverandor implements IFDBLeverandor {
	private Connection con;
	
	public DBLeverandor() {
		con = DBConnection.getInstance().getDBcon();
	}
	
	public Leverandor findLeverandor(int leverandorID, boolean retriveAssociation)
    {   String wClause = "  leverandorid = '" + leverandorID + "'";
        return singleWhere(wClause, retriveAssociation);
    }
	
	private Leverandor singleWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		Leverandor lObj = new Leverandor();
                
	        String query =  buildQuery(wClause);
                System.out.println(query);
		try{ // read the employee from the database
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
	 		if( results.next() ){
                            lObj = buildLeverandor(results);
                            //assocaition is to be build
                            stmt.close();
                            
			}
                        else{ //no employee was found
                            lObj = null;
                        }
		}//end try	
	 	catch(Exception e){
	 		System.out.println("Query exception: "+e);
	 	}
		return lObj;
	}
	
	private String buildQuery(String wClause)
	{
	    String query="SELECT navn, adresse, leverandorid  FROM leverandor";
		
		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;
			
		return query;
	}
	
	private Leverandor buildLeverandor(ResultSet results)
    {   Leverandor lObj = new Leverandor();
        try{ // the columns from the table employee  are used
              lObj.setNavn(results.getString("navn"));
              lObj.setAdresse(results.getString("adresse"));
              lObj.setLeverandorID(results.getInt("LeverandorID"));
              }
       catch(Exception e)
       {
           System.out.println("error in building the employee object");
       }
       return lObj;
    }
	
}
